package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.OverflowListDao;
import com.atguigu.jxc.dao.OverflowListGoodsDao;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.entity.*;
import com.atguigu.jxc.service.OverflowListGoodsService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OverflowListGoodsServiceImpl implements OverflowListGoodsService {
    @Autowired
    UserDao userDao;
    @Autowired
    OverflowListDao overflowListDao;
    @Autowired
    OverflowListGoodsDao overflowListGoodsDao;

    @Override
    public Map<String, Object> goodsList(Integer overflowListId) {
        List<OverflowListGoods> list=overflowListGoodsDao.goodsList(overflowListId);
        Map<String ,Object> map=new HashMap<>();
        map.put("rows",list);
        return map;
    }

    @Override
    public Map<String, Object> list(String sTime, String eTime) {
        List<OverflowList> list=overflowListDao.list(sTime,eTime);
        Map<String ,Object> map=new HashMap<>();
        map.put("rows",list);
        return map;
    }

    @Override
    public void save(String overflowNumber, OverflowList overflowList, String overflowListGoodsStr) {
        List<OverflowListGoods> list =null;
        try {
            list=new ObjectMapper().readValue(overflowListGoodsStr, new TypeReference<List<OverflowListGoods>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        User user = userDao.findUserByName((String) SecurityUtils.getSubject().getPrincipal());
        overflowList.setUserId(user.getUserId());
        overflowList.setOverflowNumber(overflowNumber);
        overflowListDao.insert(overflowList);
        Integer overflowListId = overflowList.getOverflowListId();
        for (OverflowListGoods overflowListGoods : list) {
            overflowListGoods.setOverflowListId(overflowListId);
        }
        overflowListGoodsDao.batchInsert(list);
    }
}
